package com.liyunc.demo.service;
/**
 * Copyright (c) 2018-2022 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.liyunc.demo.model.entity.PermissionInfo;
import com.liyunc.demo.model.entity.UserInfo;
import com.liyunc.demo.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author
 * @version 1.0
 * @file
 * @brief
 * @details
 * @date 2022-02-24
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-02-24                       Created
 */
@Service
public class PermissionService extends BaseService {

    @Autowired
    private EntityManager entityManager;

    /**
     * 获取某个用户的所有权限.
     */
    public Optional<List<PermissionInfo>> findAllByUser(UserInfo userInfo) {
        long userId = userInfo.getId();
        if (userId <= 0) {
            return Optional.empty();
        }
        String hql = "select permissionInfo.* "
            + "from user_info userInfo "
            + "left join user_role userRole on userInfo.id = userRole.user_id "
            + "left join role_info roleInfo on userInfo.id = roleInfo.id "
            + "left join role_permission RolePermission on roleInfo.id = RolePermission.role_id "
            +
            "left join permission_info permissionInfo on RolePermission.role_id = permissionInfo.id "
            + "where userInfo.id = ?1";
        Query countQuery = entityManager.createNativeQuery(hql, PermissionInfo.class);
        countQuery.setParameter(1, userId);
        List<PermissionInfo> permissionInfoList = countQuery.getResultList();
        return Optional.of(permissionInfoList);
    }

    /**
     * 获取当前用户的所有权限.
     */
    public Optional<Set<PermissionInfo>> findAllByCurrent() {
        UserInfo userInfo = currentUser();
        Set<PermissionInfo> permissions = permissionInfoRepository.findAllByUser(userInfo.getId());
        return Optional.of(permissions);
    }

}
